using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using VotingSystem.Data;
using VotingSystem.Models;
using VotingSystem.ViewModels;
using Microsoft.AspNetCore.Http;
using System.IO;
using Microsoft.AspNetCore.Http.Features;
using System.Security.Claims;

namespace VotingSystem.Controllers
{
    public class VoteController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly ILogger<VoteController> _logger;

        public VoteController(
            ApplicationDbContext context,
            UserManager<ApplicationUser> userManager,
            ILogger<VoteController> logger)
        {
            _context = context;
            _userManager = userManager;
            _logger = logger;
        }

        // GET: Vote
        public async Task<IActionResult> Index(string filter = "all")
        {
            var userId = User.Identity?.IsAuthenticated == true ? 
                _context.Users.FirstOrDefault(u => u.UserName == User.Identity.Name)?.Id : null;

            if (userId == null)
            {
                return RedirectToAction("Login", "Account", new { returnUrl = Url.Action("Index", "Vote") });
            }

            IQueryable<Vote> query = _context.Votes
                .Include(v => v.Options)
                .Include(v => v.Creator)
                .Include(v => v.Records)
                .Where(v => v.Records.Any(r => r.UserId == userId));
                
            // 应用筛选
            switch (filter)
            {
                case "active":
                    query = query.Where(v => v.EndTime > DateTime.Now);
                    break;
                case "ended":
                    query = query.Where(v => v.EndTime <= DateTime.Now);
                    break;
                default: // "all"
                    // 不需要额外筛选
                    break;
            }

            var votes = await query
                .OrderByDescending(v => v.CreateTime)
                .ToListAsync();

            ViewBag.CurrentFilter = filter;

            var viewModel = new VoteListViewModel
            {
                Votes = votes.Select(v => new VoteListItemViewModel
                {
                    Id = v.Id,
                    Title = v.Title,
                    Description = v.Description,
                    CreatorName = v.Creator?.UserName ?? "未知",
                    CreatedAt = v.CreateTime,
                    IsActive = v.IsActive,
                    TotalVotes = v.Records.Count,
                    MaxVotes = v.MaxVotesPerUser,
                    IsPublic = v.IsPublic,
                    IsAnonymous = v.IsAnonymous
                })
            };

            return View(viewModel);
        }

        // GET: Vote/Details/5
        public async Task<IActionResult> Details(int id, string? token = null)
        {
            var vote = await _context.Votes
                .Include(v => v.Creator)
                .Include(v => v.Options)
                .FirstOrDefaultAsync(v => v.Id == id);

            if (vote == null || vote.Creator == null)
            {
                return NotFound();
            }

            // 检查访问权限
            var hasAccess = User.Identity?.Name == vote.Creator.UserName || 
                           (!string.IsNullOrEmpty(token) && vote.AccessToken == token);

            if (!hasAccess)
            {
                // 如果是创建者，直接重定向到带token的URL
                if (User.Identity?.Name == vote.Creator.UserName)
                {
                    return RedirectToAction(nameof(Details), new { id = vote.Id, token = vote.AccessToken });
                }
                return RedirectToAction("AccessDenied", "Account", new { returnUrl = $"/Vote/Index" });
            }

            var userId = User.Identity?.IsAuthenticated == true ? 
                _context.Users.FirstOrDefault(u => u.UserName == User.Identity.Name)?.Id : null;

            // 统计当前用户已投票次数
            int userVoteCount = 0;
            if (userId != null)
            {
                userVoteCount = await _context.VoteRecords.CountAsync(r => r.VoteId == id && r.UserId == userId);
            }

            var hasVoted = userVoteCount > 0;
            var canVote = vote.EndTime > DateTime.Now && (!vote.RequireLogin || userId != null) && userVoteCount < vote.MaxVotesPerUser;

            // 查询当前用户的投票记录
            List<UserVoteRecordViewModel> myVoteRecords = new();
            if (userId != null)
            {
                myVoteRecords = await _context.VoteRecords
                    .Where(r => r.VoteId == id && r.UserId == userId)
                    .Join(_context.VoteOptions, r => r.OptionId, o => o.Id, (r, o) => new UserVoteRecordViewModel
                    {
                        OptionTitle = o.Title,
                        VoteTime = r.VoteTime,
                        Rating = r.Rating
                    }).ToListAsync();
            }

            // 获取参与者信息
            List<ParticipantViewModel>? participants = null;
            if (!vote.IsAnonymous)
            {
                participants = await _context.VoteRecords
                    .Where(r => r.VoteId == id)
                    .Join(_context.Users, r => r.UserId, u => u.Id, (r, u) => new { Record = r, User = u })
                    .GroupBy(x => x.User.Id) // 按用户ID分组，确保每个用户只显示一次
                    .Select(g => new ParticipantViewModel
                    {
                        Name = g.First().User.UserName ?? "未知用户",
                        AvatarUrl = null,
                        VoteTime = g.Max(x => x.Record.VoteTime) // 使用最新的投票时间
                    })
                    .OrderByDescending(p => p.VoteTime)
                    .ToListAsync();
            }

            bool isCreator = vote.CreatorId == userId;

            var needLogin = vote.RequireLogin && userId == null;

            var viewModel = new VoteViewModel
            {
                Id = vote.Id,
                Title = vote.Title,
                Description = vote.Description,
                CreateTime = vote.CreateTime,
                EndTime = vote.EndTime,
                IsPublic = vote.IsPublic,
                IsAnonymous = vote.IsAnonymous,
                RequireLogin = vote.RequireLogin,
                Type = vote.Type,
                MaxVotesPerUser = vote.MaxVotesPerUser,
                ResultVisibility = vote.ResultVisibility,
                Password = vote.Password,
                AllowModify = vote.AllowModify,
                ShowResultsAfterEnd = vote.ShowResultsAfterEnd,
                AccessToken = vote.AccessToken,
                TotalVotes = vote.Options.Sum(o => o.Votes),
                HasVoted = hasVoted,
                IsActive = vote.EndTime > DateTime.Now,
                IsEnded = vote.EndTime <= DateTime.Now,
                User = User,
                IsCreator = isCreator,
                NeedLogin = needLogin,
                Options = vote.Options.Select(o => new VoteOptionViewModel
                {
                    Id = o.Id,
                    Title = o.Title,
                    Description = o.Description,
                    ImageUrl = o.ImageUrl,
                    Votes = o.Votes,
                    MaxRating = o.MaxRating,
                    RatingDescription = o.RatingDescription,
                    AverageRating = o.AverageRating
                }).ToList(),
                UserVoteCount = userVoteCount,
                CanVote = canVote,
                MyVoteRecords = myVoteRecords,
                Participants = participants
            };

            return View(viewModel);
        }

        // GET: Vote/Create
        [Authorize]
        public IActionResult Create()
        {
            return View(new VoteCreateViewModel
            {
                Options = new List<VoteOptionCreateViewModel>
                {
                    new VoteOptionCreateViewModel(),
                    new VoteOptionCreateViewModel()
                }
            });
        }

        // POST: Vote/Create
        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(VoteCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userId = _userManager.GetUserId(User);
                if (string.IsNullOrEmpty(userId))
                {
                    return Unauthorized();
                }

                var vote = new Vote
                {
                    Title = model.Title,
                    Description = model.Description,
                    CreateTime = DateTime.Now,
                    EndTime = model.EndTime,
                    IsPublic = model.IsPublic,
                    IsAnonymous = model.IsAnonymous,
                    RequireLogin = model.RequireLogin,
                    Type = model.Type,
                    MaxVotesPerUser = (model.Type == VoteType.Multiple) ? model.MaxVotesPerUser : 1,
                    ResultVisibility = model.ResultVisibility,
                    Password = model.Password,
                    AllowModify = model.AllowModify,
                    ShowResultsAfterEnd = model.ShowResultsAfterEnd,
                    CreatorId = userId,
                    Options = new List<VoteOption>(),
                    AccessToken = Guid.NewGuid().ToString("N")
                };

                // 处理选项和图片上传
                foreach (var optionModel in model.Options)
                {
                    var option = new VoteOption
                    {
                        Title = optionModel.Title,
                        Description = optionModel.Description,
                        MaxRating = optionModel.MaxRating,
                        RatingDescription = optionModel.RatingDescription
                    };

                    // 处理图片上传
                    if (optionModel.Image != null && optionModel.Image.Length > 0)
                    {
                        // 确保上传目录存在
                        var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", "vote-images");
                        if (!Directory.Exists(uploadsFolder))
                        {
                            Directory.CreateDirectory(uploadsFolder);
                        }

                        // 生成唯一文件名
                        var uniqueFileName = $"{Guid.NewGuid()}_{optionModel.Image.FileName}";
                        var filePath = Path.Combine(uploadsFolder, uniqueFileName);

                        // 保存文件
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await optionModel.Image.CopyToAsync(stream);
                        }

                        // 设置图片URL
                        option.ImageUrl = $"/uploads/vote-images/{uniqueFileName}";
                    }
                    else if (!string.IsNullOrEmpty(optionModel.ImageUrl))
                    {
                        // 如果提供了图片URL，直接使用
                        option.ImageUrl = optionModel.ImageUrl;
                    }

                    vote.Options.Add(option);
                }

                _context.Votes.Add(vote);
                await _context.SaveChangesAsync();
                _logger.LogInformation("用户 {UserName} 创建了投票 {VoteId}", User.Identity?.Name, vote.Id);

                return RedirectToAction(nameof(Details), new { id = vote.Id });
            }

            return View(model);
        }

        // POST: Vote/Vote/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Vote(int id, IFormCollection form)
        {
            var vote = await _context.Votes
                .Include(v => v.Options)
                .FirstOrDefaultAsync(v => v.Id == id);

            if (vote == null)
            {
                return NotFound();
            }

            if (vote.EndTime <= DateTime.Now)
            {
                return BadRequest("投票已结束");
            }

            string? password = form["password"].ToString();
            if (!string.IsNullOrEmpty(vote.Password) && vote.Password != password)
            {
                ModelState.AddModelError("Password", "投票密码错误");
                return RedirectToAction(nameof(Details), new { id = vote.Id });
            }

            var userId = User.Identity?.IsAuthenticated == true ?
                _context.Users.FirstOrDefault(u => u.UserName == User.Identity.Name)?.Id : null;

            // 仅当投票要求登录时才强制登录
            if (vote.RequireLogin && userId == null)
            {
                TempData["NeedLoginVote"] = "该投票需要登录后才能参与，请先登录。";
                return RedirectToAction("Index", "Vote");
            }

            // 统计当前用户是否已投票
            bool hasVoted = false;
            if (userId != null)
            {
                hasVoted = await _context.VoteRecords.AnyAsync(r => r.VoteId == id && r.UserId == userId);
                if (hasVoted && !vote.AllowModify)
                {
                    ModelState.AddModelError("", "你已投票，不能再次投票。");
                    return RedirectToAction(nameof(Details), new { id = vote.Id });
                }
                // 如果允许修改，先删除原有投票记录并回退票数
                if (hasVoted && vote.AllowModify)
                {
                    var oldRecords = _context.VoteRecords.Where(r => r.VoteId == id && r.UserId == userId).ToList();
                    foreach (var record in oldRecords)
                    {
                        var option = vote.Options.FirstOrDefault(o => o.Id == record.OptionId);
                        if (option != null && option.Votes > 0)
                            option.Votes--;
                    }
                    _context.VoteRecords.RemoveRange(oldRecords);
                }
            }

            if (vote.Type == VoteType.Rating)
            {
                var ratings = new Dictionary<int, int>();
                foreach (var key in form.Keys)
                {
                    if (key.StartsWith("ratings[") && key.EndsWith("]"))
                    {
                        var optionIdStr = key.Substring(8, key.Length - 9);
                        if (int.TryParse(optionIdStr, out int optionId) &&
                            int.TryParse(form[key].ToString(), out int rating))
                        {
                            ratings[optionId] = rating;
                        }
                    }
                }

                if (!ratings.Any())
                {
                    ModelState.AddModelError("", "请至少对一个选项进行评分");
                    return RedirectToAction(nameof(Details), new { id = vote.Id });
                }

                foreach (var rating in ratings)
                {
                    var option = vote.Options.FirstOrDefault(o => o.Id == rating.Key);
                    if (option != null)
                    {
                        option.Votes++;
                        option.TotalRating += rating.Value;
                        option.AverageRating = option.TotalRating / (double)option.Votes;
                        
                        // 为每个评分选项创建投票记录
                        var voteRecord = new VoteRecord
                        {
                            VoteId = vote.Id,
                            OptionId = rating.Key,
                            UserId = userId,
                            VoteTime = DateTime.Now,
                            Rating = rating.Value
                        };
                        _context.VoteRecords.Add(voteRecord);
                    }
                }
            }
            else if (vote.Type == VoteType.Multiple)
            {
                var selectedOptions = form["selectedOptions"].ToArray();
                if (selectedOptions.Length == 0)
                {
                    ModelState.AddModelError("", "请至少选择一个选项");
                    return RedirectToAction(nameof(Details), new { id = vote.Id });
                }
                if (selectedOptions.Length > vote.MaxVotesPerUser)
                {
                    ModelState.AddModelError("", $"最多只能选择 {vote.MaxVotesPerUser} 个选项");
                    return RedirectToAction(nameof(Details), new { id = vote.Id });
                }
                
                // 为每个选择的选项创建一条投票记录
                foreach (var optionId in selectedOptions)
                {
                    if (int.TryParse(optionId, out int optionIdValue))
                    {
                        var option = vote.Options.FirstOrDefault(o => o.Id == optionIdValue);
                        if (option != null)
                        {
                            option.Votes++;
                            
                            // 为每个选项创建一条投票记录
                            var voteRecord = new VoteRecord
                            {
                                VoteId = vote.Id,
                                OptionId = optionIdValue,
                                UserId = userId,
                                VoteTime = DateTime.Now,
                                SelectedOptionsCount = selectedOptions.Length
                            };
                            _context.VoteRecords.Add(voteRecord);
                        }
                    }
                }
            }
            else // 单选
            {
                var selectedOptions = form["selectedOptions"].ToArray();
                if (selectedOptions.Length == 0)
                {
                    ModelState.AddModelError("", "请至少选择一个选项");
                    return RedirectToAction(nameof(Details), new { id = vote.Id });
                }
                if (selectedOptions.Length > 1)
                {
                    ModelState.AddModelError("", "单选投票只能选择一个选项");
                    return RedirectToAction(nameof(Details), new { id = vote.Id });
                }
                if (int.TryParse(selectedOptions[0], out int optionIdValue))
                {
                    var option = vote.Options.FirstOrDefault(o => o.Id == optionIdValue);
                    if (option != null)
                    {
                        option.Votes++;
                        // 新增：插入投票记录
                        var voteRecord = new VoteRecord
                        {
                            VoteId = vote.Id,
                            OptionId = option.Id,
                            UserId = userId,
                            VoteTime = DateTime.Now,
                            SelectedOptionsCount = 1
                        };
                        _context.VoteRecords.Add(voteRecord);
                    }
                }
            }

            await _context.SaveChangesAsync();

            return RedirectToAction(nameof(Details), new { id = vote.Id });
        }

        // GET: Vote/MyVotes
        [Authorize]
        public async Task<IActionResult> MyVotes(string filter = "all")
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            if (string.IsNullOrEmpty(userId))
            {
                return RedirectToAction("Login", "Account");
            }

            IQueryable<Vote> query = _context.Votes
                .Include(v => v.Options)
                .Include(v => v.Creator)
                .Include(v => v.Records)
                .Where(v => v.CreatorId == userId);

            // 应用筛选
            switch (filter)
            {
                case "active":
                    query = query.Where(v => v.EndTime > DateTime.Now);
                    break;
                case "ended":
                    query = query.Where(v => v.EndTime <= DateTime.Now);
                    break;
                default: // "all"
                    // 不需要额外筛选
                    break;
            }

            var votes = await query
                .OrderByDescending(v => v.CreateTime)
                .ToListAsync();

            ViewBag.CurrentFilter = filter;

            var viewModel = new VoteListViewModel
            {
                Votes = votes.Select(v => new VoteListItemViewModel
                {
                    Id = v.Id,
                    Title = v.Title,
                    Description = v.Description,
                    CreatorName = v.Creator?.UserName ?? "未知",
                    CreatedAt = v.CreateTime,
                    IsActive = v.IsActive,
                    TotalVotes = v.Records.Count,
                    MaxVotes = v.MaxVotesPerUser,
                    IsPublic = v.IsPublic,
                    IsAnonymous = v.IsAnonymous
                })
            };

            return View(viewModel);
        }

        // POST: Vote/Close/5
        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Close(int id)
        {
            var vote = await _context.Votes
                .Include(v => v.Creator)
                .FirstOrDefaultAsync(v => v.Id == id);

            if (vote == null)
            {
                return NotFound();
            }

            if (vote.Creator.UserName != User.Identity.Name)
            {
                return RedirectToAction("AccessDenied", "Account", new { returnUrl = $"/Vote/Details/{id}" });
            }

            vote.EndTime = DateTime.Now;
            await _context.SaveChangesAsync();
            _logger.LogInformation("投票 {VoteId} 已被关闭", vote.Id);

            return RedirectToAction(nameof(Details), new { id = vote.Id });
        }

        // POST: Vote/Delete/5
        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            var vote = await _context.Votes
                .Include(v => v.Creator)
                .FirstOrDefaultAsync(v => v.Id == id);

            if (vote == null)
            {
                return NotFound();
            }

            if (vote.Creator.UserName != User.Identity.Name)
            {
                return RedirectToAction("AccessDenied", "Account", new { returnUrl = $"/Vote/Details/{id}" });
            }

            _context.Votes.Remove(vote);
            await _context.SaveChangesAsync();
            _logger.LogInformation("投票 {VoteId} 已被删除", vote.Id);

            return RedirectToAction(nameof(MyVotes));
        }

        // GET: Vote/Edit/5
        [Authorize]
        public async Task<IActionResult> Edit(int id)
        {
            var vote = await _context.Votes
                .Include(v => v.Creator)
                .Include(v => v.Options)
                .FirstOrDefaultAsync(v => v.Id == id);

            if (vote == null)
            {
                return NotFound();
            }

            if (vote.Creator.UserName != User.Identity.Name)
            {
                return RedirectToAction("AccessDenied", "Account", new { returnUrl = $"/Vote/Details/{id}" });
            }

            if (vote.EndTime <= DateTime.Now)
            {
                return BadRequest("已结束的投票不能编辑");
            }

            var viewModel = new VoteEditViewModel
            {
                Id = vote.Id,
                Title = vote.Title,
                Description = vote.Description,
                EndTime = vote.EndTime,
                IsPublic = vote.IsPublic,
                IsAnonymous = vote.IsAnonymous,
                RequireLogin = vote.RequireLogin,
                Type = vote.Type,
                MaxVotesPerUser = vote.MaxVotesPerUser,
                ResultVisibility = vote.ResultVisibility,
                Password = vote.Password,
                AllowModify = vote.AllowModify,
                ShowResultsAfterEnd = vote.ShowResultsAfterEnd,
                Options = vote.Options.Select(o => new VoteOptionEditViewModel
                {
                    Id = o.Id,
                    Title = o.Title,
                    Description = o.Description,
                    ImageUrl = o.ImageUrl
                }).ToList()
            };

            return View(viewModel);
        }

        // POST: Vote/Edit/5
        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, VoteEditViewModel model)
        {
            if (id != model.Id)
            {
                return NotFound();
            }

            var vote = await _context.Votes
                .Include(v => v.Creator)
                .Include(v => v.Options)
                .FirstOrDefaultAsync(v => v.Id == id);

            if (vote == null)
            {
                return NotFound();
            }

            if (vote.Creator.UserName != User.Identity.Name)
            {
                return RedirectToAction("AccessDenied", "Account", new { returnUrl = $"/Vote/Details/{id}" });
            }

            if (vote.EndTime <= DateTime.Now)
            {
                return BadRequest("已结束的投票不能编辑");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    vote.Title = model.Title;
                    vote.Description = model.Description;
                    vote.EndTime = model.EndTime;
                    vote.IsPublic = model.IsPublic;
                    vote.IsAnonymous = model.IsAnonymous;
                    vote.RequireLogin = model.RequireLogin;
                    vote.Type = model.Type;
                    vote.MaxVotesPerUser = model.MaxVotesPerUser;
                    vote.ResultVisibility = model.ResultVisibility;
                    vote.Password = model.Password;
                    vote.AllowModify = model.AllowModify;
                    vote.ShowResultsAfterEnd = model.ShowResultsAfterEnd;

                    // 更新选项
                    foreach (var optionModel in model.Options)
                    {
                        var option = vote.Options.FirstOrDefault(o => o.Id == optionModel.Id);
                        if (option != null)
                        {
                            option.Title = optionModel.Title;
                            option.Description = optionModel.Description;
                            option.ImageUrl = optionModel.ImageUrl;
                        }
                    }

                    await _context.SaveChangesAsync();
                    _logger.LogInformation("投票 {VoteId} 已被编辑", vote.Id);
                    return RedirectToAction(nameof(Details), new { id = vote.Id });
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!await _context.Votes.AnyAsync(v => v.Id == id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            return View(model);
        }

        // GET: Vote/Results/5
        public async Task<IActionResult> Results(int id, string? token = null)
        {
            var vote = await _context.Votes
                .Include(v => v.Creator)
                .Include(v => v.Options)
                .FirstOrDefaultAsync(v => v.Id == id);

            if (vote == null)
            {
                return NotFound();
            }

            // 检查访问权限
            var hasAccess = User.Identity?.Name == vote.Creator.UserName || 
                           (!string.IsNullOrEmpty(token) && vote.AccessToken == token);

            if (!hasAccess)
            {
                // 如果是创建者，直接重定向到带token的URL
                if (User.Identity?.Name == vote.Creator.UserName)
                {
                    return RedirectToAction(nameof(Results), new { id = vote.Id, token = vote.AccessToken });
                }
                return RedirectToAction("AccessDenied", "Account", new { returnUrl = $"/Vote/Index" });
            }

            var userId = User.Identity?.IsAuthenticated == true ? 
                _context.Users.FirstOrDefault(u => u.UserName == User.Identity.Name)?.Id : null;

            // 统计当前用户已投票次数和是否已投票
            int userVoteCount = 0;
            bool hasVoted = false;
            if (userId != null)
            {
                userVoteCount = await _context.VoteRecords.CountAsync(r => r.VoteId == id && r.UserId == userId);
                hasVoted = userVoteCount > 0;
            }

            // 获取参与者信息
            List<ParticipantViewModel>? participants = null;
            if (!vote.IsAnonymous)
            {
                participants = await _context.VoteRecords
                    .Where(r => r.VoteId == id)
                    .Join(_context.Users, r => r.UserId, u => u.Id, (r, u) => new { Record = r, User = u })
                    .GroupBy(x => x.User.Id) // 按用户ID分组，确保每个用户只显示一次
                    .Select(g => new ParticipantViewModel
                    {
                        Name = g.First().User.UserName ?? "未知用户",
                        AvatarUrl = null,
                        VoteTime = g.Max(x => x.Record.VoteTime) // 使用最新的投票时间
                    })
                    .OrderByDescending(p => p.VoteTime)
                    .ToListAsync();
            }

            bool isCreator = vote.CreatorId == userId;

            var viewModel = new VoteViewModel
            {
                Id = vote.Id,
                Title = vote.Title,
                Description = vote.Description,
                CreateTime = vote.CreateTime,
                EndTime = vote.EndTime,
                IsPublic = vote.IsPublic,
                IsAnonymous = vote.IsAnonymous,
                RequireLogin = vote.RequireLogin,
                Type = vote.Type,
                MaxVotesPerUser = vote.MaxVotesPerUser,
                ResultVisibility = vote.ResultVisibility,
                Password = vote.Password,
                AllowModify = vote.AllowModify,
                ShowResultsAfterEnd = vote.ShowResultsAfterEnd,
                AccessToken = vote.AccessToken,
                TotalVotes = vote.Options.Sum(o => o.Votes),
                IsActive = vote.EndTime > DateTime.Now,
                IsEnded = vote.EndTime <= DateTime.Now,
                User = User,
                IsCreator = isCreator,
                HasVoted = hasVoted,
                UserVoteCount = userVoteCount
            };

            if (!viewModel.CanViewResults)
            {
                return RedirectToAction("AccessDenied", "Account", new { returnUrl = $"/Vote/Details/{id}" });
            }

            // 获取参与者信息 (只有在允许查看结果时才需要)
            participants = await _context.VoteRecords
                .Where(r => r.VoteId == id)
                .Join(_context.Users, r => r.UserId, u => u.Id, (r, u) => new { Record = r, User = u })
                .GroupBy(x => x.User.Id) // 按用户ID分组，确保每个用户只显示一次
                .Select(g => new ParticipantViewModel
                {
                    Name = g.First().User.UserName ?? "未知用户",
                    AvatarUrl = null,
                    VoteTime = g.Max(x => x.Record.VoteTime) // 使用最新的投票时间
                })
                .OrderByDescending(p => p.VoteTime)
                .ToListAsync();

            // 再次创建 ViewModel，这次包含 participants
            var finalViewModel = new VoteViewModel
            {
                Id = vote.Id,
                Title = vote.Title,
                Description = vote.Description,
                CreateTime = vote.CreateTime,
                EndTime = vote.EndTime,
                IsPublic = vote.IsPublic,
                IsAnonymous = vote.IsAnonymous,
                RequireLogin = vote.RequireLogin,
                Type = vote.Type,
                MaxVotesPerUser = vote.MaxVotesPerUser,
                ResultVisibility = vote.ResultVisibility,
                Password = vote.Password,
                AllowModify = vote.AllowModify,
                ShowResultsAfterEnd = vote.ShowResultsAfterEnd,
                AccessToken = vote.AccessToken,
                TotalVotes = vote.Options.Sum(o => o.Votes),
                IsActive = vote.EndTime > DateTime.Now,
                IsEnded = vote.EndTime <= DateTime.Now,
                User = User,
                IsCreator = isCreator,
                HasVoted = hasVoted,
                UserVoteCount = userVoteCount,
                Options = vote.Options.Select(o => new VoteOptionViewModel
                {
                    Id = o.Id,
                    Title = o.Title,
                    Description = o.Description,
                    ImageUrl = o.ImageUrl,
                    Votes = o.Votes,
                    MaxRating = o.MaxRating,
                    RatingDescription = o.RatingDescription,
                    AverageRating = o.AverageRating
                }).ToList(),
                Participants = participants
            };

            return View(finalViewModel);
        }
    }
} 